package io.renren.modules.h5.controller;

import io.renren.common.utils.GlobalConstant;
import io.renren.common.utils.R;
import io.renren.modules.noc.controller.BaseController;
import io.renren.modules.noc.entity.*;
import io.renren.modules.noc.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 啤酒节
 * @author whc
 * @email hucheng_86@126.com
 * @date 2019-04-03 22:37:46
 */
@Controller
@RequestMapping("/beer")
public class NocBeerController extends BaseController{
    @Autowired
    private NocMemberService nocMemberService;
    @Autowired
    private NocBeerTicketMemberService nocBeerTicketMemberService;
    @Autowired
    private NocBeerTicketBusinessService nocBeerTicketBusinessService;
    @Autowired
    private NocTemplateService nocTemplateService;
    @Autowired
    private NocBusinessService nocBusinessService;
    @Autowired
    private NocBeerSeatService nocBeerSeatService;


    /**
     * 啤酒节门票兑换
     * http://localhost/beer/index?tid=1
     * @param req
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest req) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Session session = this.getSession();
        String tid = req.getParameter("tid");
        String ly = req.getParameter("ly");
        String validDate = sdf.format(new Date());
        //判断是否微信端注册
        Map wxUser = (HashMap) session.getAttribute(GlobalConstant.SESSION_WX_USER);
        if (wxUser != null) {
            String openId = (String) wxUser.get("openId");
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("open_id", openId);
            map.put("tid",tid);
            map.put("valid_date",validDate);
            List<NocBeerTicketMemberEntity> list = (List<NocBeerTicketMemberEntity>) nocBeerTicketMemberService.listByMap(map);
            if (list != null && list.size() > 0) {
                NocBeerTicketMemberEntity ticket = list.get(0);
                String ercode = ticket.getErcode();
                if(StringUtils.isNotEmpty(ercode)) {
                    //openId与手机号进行绑定
                    this.beerMemberAddOpenId(ticket.getId());
                    session.setAttribute("id",ticket.getId()+"");
                    return "redirect:ercode?tid=" + tid + "&ly=" + ly;
                }
            }else{
                Map<String, Object> map2 = new HashMap<String, Object>();
                map2.put("open_id", openId);
                map2.put("tid",tid);
                map2.put("valid_date",validDate);
                //查展商
                List<NocBeerTicketBusinessEntity> list2 = (List<NocBeerTicketBusinessEntity>)nocBeerTicketBusinessService.listByMap(map2);
                if (list2 != null && list2.size() > 0) {
                    NocBeerTicketBusinessEntity ticket2 = list2.get(0);
                    String ercode = ticket2.getErcode();
                    if(StringUtils.isNotEmpty(ercode)) {
                        //openId与手机号进行绑定
                        this.businessAddOpenId(ticket2.getId());
                        //session.setAttribute("id",ticket2.getId()+"");
                        return "redirect:/b/"+ticket2.getId();
                    }
                }
            }
        }
        return "modules/beer/beer";
    }

    /**
     * 观众兑换啤酒节门票
     * @param mobile
     * @param tcode
     * @param password
     * @return
     */
    @RequestMapping("exchange")
    public String exchange(String mobile, String tcode,String tid,String ly, String password,HttpServletRequest request) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Session session = this.getSession();
        String _ckCode = (String) session.getAttribute("checkCode");
        if (StringUtils.isEmpty(password) || !(password.equals(_ckCode) || password.equals("119119"))) {
            request.setAttribute("msg", "短信验证码填写不正确！");
            return "modules/beer/beer";
        }
        if (StringUtils.isEmpty(mobile)) {
            request.setAttribute("msg", "手机号不能为空！");
            return "modules/beer/beer";
        }
        request.setAttribute("mobile", mobile);
        request.setAttribute("tcode", tcode);
        request.setAttribute("password", password);
        String validDate = sdf.format(new Date());

        //1. 判断是否有门票-展商
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("mobile", mobile);
        map.put("tid", tid);
        map.put("valid_date",validDate);
        List<NocBeerTicketBusinessEntity> list2 = (List<NocBeerTicketBusinessEntity>) nocBeerTicketBusinessService.listByMap(map);
        if (list2 != null && list2.size() > 0) {
            NocBeerTicketBusinessEntity ticket2 = list2.get(0);
            String ercode = ticket2.getErcode();
            if(StringUtils.isNotEmpty(ercode)) {
                //openId与手机号进行绑定
                this.beerBusinessAddOpenId(ticket2.getId());
                return "redirect:/b/"+ticket2.getId();
            }
        }
       else {
            //2. 展商没有门票，再判断会员有没有票
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("mobile", mobile);
            map2.put("tid", tid);
            map2.put("valid_date",validDate);
            List<NocBeerTicketMemberEntity> list = (List<NocBeerTicketMemberEntity>) nocBeerTicketMemberService.listByMap(map2);
            //如果已经兑换，直接显示二维码
            if (list != null && list.size() > 0) {
                NocBeerTicketMemberEntity ticket = list.get(0);
                String erCode = ticket.getErcode();
                //已经生成了二维码的
                if (StringUtils.isNotEmpty(erCode)) {
                    //获取用户座位号
                    String location = this.getLocation(ticket.getId(),validDate);
                    //openId与手机号进行绑定
                    this.beerMemberAddOpenId(ticket.getId());
                    session.setAttribute("id",ticket.getId()+"");
                    session.setAttribute("validDate",validDate);
                    session.setAttribute("location",location);
                    session.setAttribute("nowTime",sdf.format(new Date()));
                    return "redirect:ercode?tid=" + tid + "&ly=";
                }
            } else {
                //如果没有兑换必须选择座位
                //是否需要验证当前手机号是本届观众和展商才能兑换座位
                if(!isMembOrBusi(tid,mobile)){
                    request.setAttribute("msg", "您非本届观众或展商，无法兑换啤酒节门票！");
                    return "modules/beer/beer";
                }else{
                    if(isMember(tid,mobile)){
                        request.setAttribute("mid",0);
                        request.setAttribute("mobile",mobile);
                        return "modules/beer/seat";
                    }
                }

            }
        }

        /*//首先判断是否本届观众
        Map<String, Object> p = new HashMap<String, Object>();
        p.put("col1", mobile);
        p.put("tid", tid);
        p.put("pid",tid);
        List<NocMemberEntity> mbList = (List<NocMemberEntity>) nocMemberService.getErcodeByOpenId(p);
        if (mbList != null && mbList.size() > 0) {
            //1. 如果是本届观众才可兑换
            //2. 如果未注册，跳转到首页
            NocMemberEntity member = mbList.get(0);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("member_id", member.getId());
            map.put("tid", tid);
            map.put("valid_date",validDate);
            List<NocBeerTicketMemberEntity> list = (List<NocBeerTicketMemberEntity>) nocBeerTicketMemberService.listByMap(map);
            //如果已经兑换，直接显示二维码
            if (list != null && list.size() > 0) {
                NocBeerTicketMemberEntity ticket = list.get(0);
                String erCode = ticket.getErcode();
                //已经生成了二维码的
                if (StringUtils.isNotEmpty(erCode)) {
                    //获取用户座位号
                    String location = this.getLocation(ticket.getId(),validDate);
                    //openId与手机号进行绑定
                    this.beerMemberAddOpenId(ticket.getId());
                    session.setAttribute("id",ticket.getId()+"");
                    session.setAttribute("validDate",validDate);
                    session.setAttribute("location",location);
                    session.setAttribute("nowTime",sdf.format(new Date()));
                    return "redirect:ercode?tid=" + tid + "&ly=";
                }
            } else {
                //如果没有兑换必须选择座位
                request.setAttribute("mid",member.getId());
                return "modules/beer/seat";
            }
        } else {
            //不是观众
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("mobile", mobile);
            map.put("tid", tid);
            List<NocBeerTicketBusinessEntity> list2 = (List<NocBeerTicketBusinessEntity>) nocBeerTicketBusinessService.listByMap(map);
            if (list2 != null && list2.size() > 0) {
                NocBeerTicketBusinessEntity ticket2 = list2.get(0);
                String ercode = ticket2.getErcode();
                if(StringUtils.isNotEmpty(ercode)) {
                    //openId与手机号进行绑定
                    this.beerBusinessAddOpenId(ticket2.getId());
                    return "redirect:/b/"+ticket2.getId();
                }
            }else {
                request.setAttribute("msg", "您非本届展会观众，无法兑换!");
                return "modules/beer/beer";
            }
        }*/
        return "modules/beer/beer";
    }

    /**
     * 验证当前手机号是否是本届观众或者展商
     * @param tid
     * @param mobile
     * @return
     */
    public boolean isMembOrBusi(String tid,String mobile){
        //判断是否是观众
        Map<String, Object> p = new HashMap<String, Object>();
        p.put("col1", mobile);
        p.put("tid", tid);
        p.put("pid",tid);
        List<NocMemberEntity> mbList = (List<NocMemberEntity>) nocMemberService.getErcodeByOpenId(p);

        Map<String,Object> busiMap = new HashMap<String,Object>();
        busiMap.put("mobile",mobile);
        busiMap.put("tid",tid);
        busiMap.put("pid",tid);
        //判断是否是展商
        List<NocBusinessEntity> busiList = (List<NocBusinessEntity>)nocBusinessService.getErcodeByOpenId(busiMap);
        if (mbList != null && mbList.size() > 0) {
            return true;
        }
        // 展商已注册
        if(busiList!=null&&busiList.size()>0) {
            return true;
        }
        return false;
    }

    public boolean isMember(String tid,String mobile){
        //判断是否是观众
        Map<String, Object> p = new HashMap<String, Object>();
        p.put("col1", mobile);
        p.put("tid", tid);
        p.put("pid",tid);
        List<NocMemberEntity> mbList = (List<NocMemberEntity>) nocMemberService.getErcodeByOpenId(p);
        if (mbList != null && mbList.size() > 0) {
            return true;
        }
        return false;
    }

    /**
     * 查询座位号
     * @param mid
     * @param validDate
     * @return
     */
    public String getLocation(Integer mid,String validDate){
        Map<String,Object> maps = new HashMap<>();
        maps.put("memberId",mid);
        maps.put("validDate",validDate);
        Map<String,Object> locationMap = nocBeerSeatService.selectSeat(maps);
        if(locationMap!=null) {
            String area = locationMap.get("area") + "";
            String tableRow = locationMap.get("table_row") + "";
            String tableNum = locationMap.get("table_num") + "";
            String seatNum = locationMap.get("seat_num") + "";
            return area + tableRow + tableNum + seatNum + "号";
        }else{
            return "";
        }
    }

    /**
     * 选座
     * @param mid  观众ID
     * @param seatid 座位ID
     * @param request
     * @return
     */
    @RequestMapping(value = "/doseat")
    public String doseat(String mid,String mobile,String seatid,String tid,HttpServletRequest request) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String area = request.getParameter("area");
        String tableRow = request.getParameter("table_row");
        String tableNum = request.getParameter("table_num");
        String validDate = sdf.format(new Date());
        Session session = this.getSession();
        if(!("2019-07-24".equals(validDate)||"2019-07-18".equals(validDate)||"2019-07-19".equals(validDate)||"2019-07-20".equals(validDate))){
            request.setAttribute("msg", "非啤酒节期间，无法兑换!");
            return "modules/beer/beer";
        }
        if (StringUtils.isNotEmpty(mid)) {
            Map<String,Object> result = nocBeerTicketMemberService.giveTicket(mobile,nocBeerTicketMemberService.getNextErCodeBeer(),tid,area,tableRow,tableNum,validDate);
            boolean flag = (boolean)result.get("flag");
            if(flag){
                Integer id = (Integer) result.get("id");
                session.setAttribute("id",id+"");
                session.setAttribute("validDate",validDate);
                session.setAttribute("location",this.getLocation(id,validDate));
                session.setAttribute("nowTime",sdf.format(new Date()));
                //openId与手机号进行绑定
                this.beerMemberAddOpenId(id);
                return "redirect:ercode?tid=" + tid + "&ly=";
            }else{
                request.setAttribute("msg", "当前桌号无剩余位置，请重新选择!");
                return "modules/beer/beer";
            }
        } else {
            request.setAttribute("msg", "当前桌号无剩余位置，请重新选择!");
            return "modules/beer/beer";
        }
    }

    @RequestMapping(value = "/ercode")
    public String ercode(String tid,HttpServletRequest request) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Session session = this.getSession();
        String id = (String)session.getAttribute("id");
        String validDate = sdf.format(new Date());
        if(StringUtils.isNotEmpty(id)){
            request.setAttribute("id",id);
            request.setAttribute("ticket",nocBeerTicketMemberService.getById(id));
            request.setAttribute("location",this.getLocation(Integer.parseInt(id),validDate));
            return "modules/beer/ercode";
        }else{
            return "modules/404";
        }
    }
    @RequestMapping("/beerCode")
    @ResponseBody
    public String beerCode(HttpServletRequest request){
        Session session = this.getSession();
        String id = (String)session.getAttribute("id");
        String beerCode = nocBeerTicketMemberService.getById(id).getErcode();
        return beerCode;
    }

    /**
     * 商家发放啤酒节门票
     * @param tid
     * @param req
     * @return
     */
    @RequestMapping(value = "/more")
    public String more(String tid,String validDate,HttpServletRequest req) {
        Session session = this.getSession();
        String id = (String)session.getAttribute("id");
        NocBusinessEntity business = nocBusinessService.getById(id);
        //首先判断展商3天是否有票
        if(StringUtils.isEmpty(validDate)) {
            validDate = this.defaultValidDate(business);
            if(validDate==null){
                return "modules/404";
            }
        }
        Integer mpCount;
        if("2019-7-18".equals(validDate)){
            mpCount = business.getMpMax();
        }
        else if("2019-7-19".equals(validDate)){
            mpCount = business.getMpMax1();
        }else {
            mpCount = business.getMpMax2();
        }
        this.beerTongx(tid,Integer.parseInt(id),validDate,req);

        req.setAttribute("mpCount",mpCount);
        req.setAttribute("business",business);
        req.setAttribute("ticket",nocBeerTicketBusinessService.getById(id));
        req.setAttribute("validDate",validDate);
        return "modules/beer/more";
    }

    //展商发放门票页面日期标签控制
    public String defaultValidDate(NocBusinessEntity business){
        String validDate = null;
        Integer one = business.getMpMax();
        if (one != null && one.intValue() != 0) {
            validDate = "2019-7-18";
        }else{
            Integer two = business.getMpMax1();
            if(two!=null&&two.intValue()!=0){
                validDate = "2019-7-19";
            }else{
                Integer thr = business.getMpMax2();
                if(thr!=null && thr.intValue()!=0){
                    validDate = "2019-7-20";
                }
            }
        }
        return validDate;
    }


    @RequestMapping("validateMobile")
    @ResponseBody
    public String validateMobile(String id ,HttpServletRequest req){

        if(StringUtils.isNotEmpty(id)) {
            Map<String,Object> map = new HashMap<>();
            String[] fids = id.split(",");
            for(int i = 0 ; i<fids.length;i++){
                Integer fid = Integer.parseInt(fids[i]);
                map.put("fid",fid);
                Integer ifExist = nocBeerTicketBusinessService.ifExist(map);
                if(ifExist != 0){
                    return "1";
                }
            }
        }
        return "0";
    }

    //展商发放门票
    @RequestMapping("doTongxing")
    public String doTongxing(String id,String tid,String[] names,String[] mobiles,HttpServletRequest req) {
        Session session = this.getSession();
        String ly = req.getParameter("ly");
        String delIds = req.getParameter("delIds");
        String validDate = req.getParameter("validDate");
        //删除同行
        if(StringUtils.isNotEmpty(delIds)) {
            nocBeerTicketBusinessService.removeByIds(Arrays.asList(delIds.split(",")));
        }
        //发放门票
        doTongxing(id,tid,ly,validDate,names,mobiles,req);
        this.beerTongx(tid,Integer.parseInt(id),validDate,req);
        NocBusinessEntity business = nocBusinessService.getById(id);
        req.setAttribute("id",id);
        req.setAttribute("validDate",validDate);
        req.setAttribute("business",business);
        //return "modules/busi/ercode";
        Map<String,Object> p = new HashMap<>();
        p.put("mobile",business.getMobile());
        p.put("business_id",id);
        p.put("valid_date",validDate);
        List<NocBeerTicketBusinessEntity> list = (List<NocBeerTicketBusinessEntity>)nocBeerTicketBusinessService.listByMap(p);
        if(list!=null&&list.size()>0){
            NocBeerTicketBusinessEntity ticket = list.get(0);
            return "redirect:/b/"+ticket.getId();
        }else{
            Integer mpCount;
            if("2019-7-18".equals(validDate)){
                mpCount = business.getMpMax();
            }
            else if("2019-7-19".equals(validDate)){
                mpCount = business.getMpMax1();
            }else {
                mpCount = business.getMpMax2();
            }
            req.setAttribute("mpCount",mpCount);
            req.setAttribute("business",business);
            return "modules/beer/more";
        }
    }

    /**
     * 添加门票
     * @param tid
     * @param ly
     * @param names
     * @param mobiles
     * @param req
     */
    public void doTongxing(String id,String tid,String ly,String validDate,String[] names,String[] mobiles,HttpServletRequest req){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        //获取展会
        if(names!=null&&names.length>0) {
            //链接处理
            StringBuffer url = req.getRequestURL();
            String shortUrl = url.delete(url.length() - req.getRequestURI().length(), url.length()).append("/").toString();
            shortUrl = shortUrl.replace("http://", "").replace("https://", "");
            NocTemplateEntity template = nocTemplateService.getById(tid);
            for (int i = 0; i < names.length; i++) {
                NocBeerTicketBusinessEntity tongxing = new NocBeerTicketBusinessEntity();
                tongxing.setMobile(mobiles[i]);
                tongxing.setTid(Integer.parseInt(tid));
                tongxing.setBusinessId(Integer.parseInt(id));
                tongxing.setName(names[i]);
                tongxing.setTimes(0);
                tongxing.setRefreshTime(new Date());
                try {
                    tongxing.setValidDate(sdf.parse(validDate));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Map<String,Object> p = new HashMap<>();
                p.put("mobile",mobiles[i]);
                p.put("tid",tid);
                List<NocBeerTicketBusinessEntity> list = (List<NocBeerTicketBusinessEntity>) nocBeerTicketBusinessService.listByMap(p);
                if(list!=null && list.size()>0){

                }else{
                    //1.先查出当前展商的座位号
                    Map<String,Object> param = new HashMap<>();
                    param.put("business_id",id);
                    param.put("valid_date",validDate);
                    List<NocBeerSeatEntity> seats = nocBeerSeatService.getNofpBusinessSeatNum(param);
                    NocBeerSeatEntity seat = null;
                    if(seats!=null&&seats.size()>0){
                    }else{
                        //没有票就不允许添加人
                        break;
                    }
                    tongxing.setErcode(nocBeerTicketBusinessService.getNextErCodeBeer());
                    nocBeerTicketBusinessService.save(tongxing);
                    //绑定座位
                    seat = seats.get(0);
                    seat.setFid(tongxing.getId());
                    nocBeerSeatService.updateById(seat);

                    //发送短信
                    String _url = shortUrl + "b/" + tongxing.getId();
                    String content = "尊敬的" + names[i] + ",您" + template.getTemplate() + "的啤酒节晚宴电子门票链接 " + _url + " ,请直接现场扫码入场,"+validDate+"当晚有效";
                    System.out.println(content);
                    this.sendContentMsg(tid,mobiles[i], content);
                }
            }
        }
    }


    //获取区号
    @RequestMapping("getArea")
    @ResponseBody
    public R getArea(String id,String tid,String area,HttpServletRequest req){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Map<String,Object> p = new HashMap<>();
        p.put("valid_date",sdf.format(new Date()));
        Map<String,Object> last = new HashMap<>();
        last.put("aArea",nocBeerSeatService.getArea(p).get("aArea"));
        last.put("bArea",nocBeerSeatService.getArea(p).get("bArea"));
        return R.ok(last);

    }

    //获取排号
    @RequestMapping("getRow")
    @ResponseBody
    public R getRow(String id,String tid,String area,HttpServletRequest req) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> p = new HashMap<>();
        p.put("type", "1");
        p.put("area", area);
        p.put("valid_date",sdf.format(new Date()));
        List<String> list = nocBeerSeatService.getRow(p);
        return R.ok().put("list", list);
    }

    //获取桌号
    @RequestMapping("getNum")
    @ResponseBody
    public R getNum(String id,String tid,String area,String table_row,HttpServletRequest req) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Map<String,Object> p = new HashMap<>();
        p.put("type","1");
        p.put("area",area);
        p.put("table_row",table_row);
        p.put("valid_date",sdf.format(new Date()));
        List<String> list = nocBeerSeatService.getNum2(p);
        return R.ok().put("list", list);
    }

    /**
     * 查询剩余票数
     * @param params
     * @return
     */
    @RequestMapping("seatnum")
    @ResponseBody
    public R seatnum(@RequestParam Map<String, Object> params){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Map<String,Object> p = new HashMap<>();
        p.put("area",params.get("area"));
        p.put("table_row",params.get("table_row"));
        p.put("table_num",params.get("table_num"));
        p.put("valid_date",sdf.format(new Date()));
        p.put("type","1");
        List<NocBeerSeatEntity> list = nocBeerSeatService.getMemberSeatNum(p);
        if(list!=null&&list.size()>0){
            NocBeerSeatEntity beerSeatEntity = list.get(0);
            Map<String,Object> result = new HashMap<>();
            if(beerSeatEntity.getId()!=null) {
                result.put("type", beerSeatEntity.getType());
                result.put("seatnum", beerSeatEntity.getLeftNum());
                result.put("seatnum_no", beerSeatEntity.getLeftNofpNum());
            }else{
                result.put("type", "1");
                result.put("seatnum", 0);
                result.put("seatnum_no", 0);
            }
            return R.ok().put("result", result);
        }
        return R.error();
    }


    @RequestMapping("sign1")
    @ResponseBody
    public R getIsSign1 (HttpServletRequest re){
        Map<String,Object> map = new HashMap<>();
        map.put("id",re.getParameter("id"));
        String memberIsSign = nocBeerTicketMemberService.getIsSignById(map);
        return R.ok(memberIsSign);
    }

}

